<template>
	<view class="boss-card" :class="statusClass">
		<!-- 顶部操作栏 -->
		<view class="card-header">
			<view class="boss-info">
				<image class="boss-image" :src="boss.image" mode="aspectFit"></image>
				<text class="boss-name">{{ boss.name }}</text>
			</view>

			<!-- 提醒开关 -->
			<view class="reminder-switch">
				<text class="reminder-label">提醒</text>
				<switch style="transform: scale(0.7);" :checked="boss.isNotify" @change="toggleNotification"
					color="#4CD964" />
			</view>
		</view>

		<!-- BOSS信息 -->
		<view class="card-content">
			<view class="refresh-info">
				<view class="map-info">
					<text class="boss-map">地图：{{ boss.map }}</text>
					<text class="refresh-cycle">刷新周期: {{ formatInterval(boss.interval) }}</text>
				</view>

				<button class="update-btn" @click="handleRefresh">
					{{boss.lastTime ? '更新刷新时间' : '记录刷新时间'}}
				</button>
			</view>


			<!-- 计时器显示 -->
			<view class="timer-display" v-if="boss.lastTime && boss.isNotify">
				<text class="remaining-time" :class="timeClass">
					{{ displayTime }}
				</text>
			</view>

			<text class="next-refresh" v-if="boss.lastTime">下次刷新: {{ nextRefreshTime }}</text>
		</view>

		<!-- 操作按钮 -->
		<view class="card-actions">
			<view class="action-btn edit-btn" @click="handleEdit">
				<uni-icons type="compose" size="22" color="#0055ff"></uni-icons>
			</view>
			<view class="action-btn delete-btn" @click="handleDelete">
				<uni-icons type="trash" size="22" color="#d9534f"></uni-icons>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		name: "boss-card",
		emits: ["refreshed", "toggle-notification", "update", "edit", "delete"],
		props: {
			boss: {
				type: Object,
				required: true,
				default: () => {}
			}
		},
		data() {
			return {
				remainingTime: 0,
				timer: null,
				currentCycle: 1,
				displayTime: '00:00:00',
				nextRefreshTime: '00:00:00',
				hasPlayedSound: false,
				intervalMS: 60000,
				notifySwitch: false
			}
		},
		computed: {
			statusClass() {
				return {
					'urgent': this.remainingTime <= this.boss.notifyBefore * 60 * 1000,
					'refreshed': this.remainingTime <= 0
				};
			},
			timeClass() {
				return {
					'normal': this.remainingTime > this.boss.notifyBefore * 60 * 1000,
					'warning': this.remainingTime <= this.boss.notifyBefore * 60 * 1000 && this.remainingTime >
						0,
					'refreshed': this.remainingTime <= 0
				};
			}
		},
		mounted() {
			this.notifySwitch = this.boss.isNotify
			this.startTimer();
			// 添加生命周期监听
			uni.onAppShow(() => {
				if (this.notifySwitch) {
					this.calculateTiming();
					this.startTimer();
				}
			});
			uni.onAppHide(() => {
				this.clearTimer();
			});

		},
		beforeDestroy() {
			this.clearTimer();
			// 移除生命周期监听
			uni.offAppShow();
			uni.offAppHide();
		},
		watch: {
			'boss.lastTime': {
				immediate: true,
				handler() {
					this.calculateTiming();
				}
			},
			'boss.interval': {
				immediate: true,
				handler() {
					this.intervalMS = this.boss.interval * 60 * 1000;
					this.calculateTiming();
				}
			}
		},
		methods: {
			startTimer() {
				this.clearTimer();
				this.updateTiming();
				if (this.notifySwitch) {
					this.timer = setInterval(this.updateTiming, 1000);
				}
			},
			clearTimer() {
				if (this.timer) {
					clearInterval(this.timer);
					this.timer = null;
				}
			},
			calculateTiming() {
				const now = Date.now();
				// 确保lastTime存在
				if (!this.boss.lastTime) return;

				// 计算经过的完整周期数
				const elapsed = now - this.boss.lastTime;
				this.currentCycle = Math.floor((now - this.boss.lastTime) / this.intervalMS) + 1;

				// 计算下次刷新时间和剩余时间
				const nextRefresh = this.boss.lastTime + (this.currentCycle * this.intervalMS);
				this.remainingTime = nextRefresh - now;

				// 如果剩余时间异常（可能是后台导致的），重置为正常值
				if (this.remainingTime > this.intervalMS || this.remainingTime < -this.intervalMS) {
					this.currentCycle = Math.floor(elapsed / this.intervalMS) + 1;
					this.remainingTime = (this.boss.lastTime + (this.currentCycle * this.intervalMS)) - now;
				}

				this.updateDisplay();
				this.checkAutoCycle();
			},
			updateTiming() {
				this.remainingTime -= 1000;
				this.updateDisplay();
				this.checkAutoCycle();

				// 触发刷新效果
				if (this.remainingTime <= 1000 && !this.hasPlayedSound) {
					this.hasPlayedSound = true
					this.$emit('refreshed', this.boss.id);
				}

				// 自动切换到下一周期
				if (this.remainingTime <= -1000) {
					this.currentCycle++;
					this.remainingTime = this.intervalMS + this.remainingTime;
					this.hasPlayedSound = false;
				}
			},
			updateDisplay() {
				// 更新时间显示
				this.displayTime = this.formatTime(Math.max(0, this.remainingTime));

				// 更新下次刷新时间
				const nextRefresh = new Date(this.boss.lastTime + (this.currentCycle * this.intervalMS));
				this.nextRefreshTime = nextRefresh.toLocaleTimeString([], { hour12: false }).slice(0, 8)
			},
			checkAutoCycle() {
				// 如果剩余时间超过一个周期（可能是手动修改了lastTime）
				if (this.remainingTime > this.intervalMS) {
					const now = Date.now()
					this.currentCycle = Math.floor((now - this.boss.lastTime) / this.intervalMS) + 1;
					this.remainingTime = (this.boss.lastTime + (this.currentCycle * this.intervalMS)) - now;
				}
			},
			formatTime(ms) {
				if (ms <= 1000) return '已刷新';

				const seconds = Math.floor(ms / 1000) % 60;
				const minutes = Math.floor(ms / (1000 * 60)) % 60;
				const hours = Math.floor(ms / (1000 * 60 * 60));

				return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
			},
			formatInterval(m) {
				const minutes = m;
				const hours = Math.floor(minutes / 60);
				const remainingMinutes = minutes % 60;

				if (hours > 0 & remainingMinutes > 0) {
					return `${hours}小时${remainingMinutes.toString().padStart(2, '0')}分钟`;
				} else if (remainingMinutes <= 0) {
					return `${hours}小时`;
				} else {
					return `${minutes}分钟`;
				}
			},
			toggleNotification(e) {
				this.notifySwitch = e.detail.value
				if (!e.detail.value) {
					this.clearTimer();
				} else {
					this.startTimer()
				}
				this.$emit('toggle-notification', {
					bossId: this.boss.id,
					enabled: e.detail.value
				});
			},
			handleRefresh() {
				if (this.isNotify) {
					this.startTimer()
				}
				this.$emit('update', this.boss.id);
			},
			handleEdit() {
				this.$emit('edit', this.boss.id);
			},
			handleDelete() {
				uni.showModal({
					title: '删除确认',
					content: `确定要删除"${this.boss.map}"的【${this.boss.name}】吗？`,
					success: (res) => {
						if (res.confirm) {
							this.$emit('delete', this.boss.id);
						}
					}
				});
			}
		}
	}
</script>

<style scoped>
	.boss-card {
		background-color: #fff;
		border-radius: 8px;
		padding: 15px;
		margin-bottom: 15px;
		position: relative;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
		border-left: 4px solid transparent;
	}

	.boss-card.urgent {
		border-left-color: #f0ad4e;
		background-color: #fffcf5;
	}

	.boss-card.refreshed {
		border-left-color: #5cb85c;
		background-color: #f5fff5;
	}

	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 10px;
	}

	.boss-info {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.boss-image {
		width: 50px;
		height: 50px;
		border-radius: 4px;
		object-fit: contain;
	}

	.boss-name {
		font-size: 16px;
		font-weight: bold;
		color: #d9534f;
		margin-right: 10px;
	}

	.update-btn {
		height: 60rpx;
		line-height: 60rpx;
		padding: 0 25rpx;
		font-size: 24rpx;
		background: linear-gradient(135deg, #3498db, #2ecc71);
		color: white;
		border-radius: 30rpx;
	}

	.reminder-switch {
		display: flex;
		align-items: center;
	}

	.reminder-label {
		font-size: 12px;
		color: #666;
		margin-right: 8px;
	}

	.card-content {
		margin-bottom: 10px;
	}

	.refresh-info {
		display: flex;
		flex-direction: row;
	}

	.map-info {
		flex: 1;
	}

	.boss-map {
		font-size: 14px;
		color: #5bc0de;
		display: block;
		margin-bottom: 5px;
	}

	.refresh-cycle {
		font-size: 12px;
		color: #666;
		display: block;
		margin-bottom: 10px;
	}

	.timer-display {
		margin: 10px 0;
		text-align: center;
	}

	.remaining-time {
		font-size: 20px;
		font-weight: bold;
		font-family: monospace;
	}

	.remaining-time.normal {
		color: #5cb85c;
	}

	.remaining-time.warning {
		color: #f0ad4e;
		animation: pulse 1s infinite;
	}

	.remaining-time.refreshed {
		color: #d9534f;
		animation: blink 1s infinite;
	}

	.next-refresh {
		font-size: 12px;
		color: #999;
		display: block;
		text-align: center;
	}

	.card-actions {
		position: absolute;
		right: 10px;
		bottom: 10px;
		display: flex;
		gap: 8px;
	}

	.action-btn {
		width: 28px;
		height: 28px;
		border-radius: 50%;
		background-color: rgba(0, 0, 0, 0.05);
		display: flex;
		align-items: center;
		justify-content: center;
	}

	@keyframes pulse {
		0% {
			transform: scale(1);
		}

		50% {
			transform: scale(1.05);
		}

		100% {
			transform: scale(1);
		}
	}

	@keyframes blink {
		0% {
			opacity: 1;
		}

		50% {
			opacity: 0.5;
		}

		100% {
			opacity: 1;
		}
	}
</style>